// pages/order/orderCheck/orderCheck.js
var app = getApp();
var appointment_time_id = '';
var scene_id = '';
var cooker_id = "";
var ch_latitude = "";
var ch_longitude = "";
var canDo = true, can_Do2 = true;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    work_order_id: '',
    orderDetail: '',//回显的订单详情
    to_door: '',//上门日期
    start_time: '',//开始选择时间
    end_time: '',
    time_list: '',//上门时间
    time_index: '',//上门索引
    server_list: [],//服务场景
    server_index: '',//
    cooker_list: [],//炉具类型
    cooker_index: '',//
    valueName: [], //设置回显选择的地址(name)
    getAreaMsg: '', //选择的地址信息
    add_ress: '',//详细地址
    imgUrl: [],//显示用的
    img_url: [],//传给服务器用的
    fanArr: [{ power: '', focal_eye: '', focal_eye_name: '', index: '' }],
    focal_eye_list: [],//灶眼类型
    cookerArr: [{ cooker_type: '', cooker_type_name: '', num: 1, water_quantity: '', gas_consumption: '', second: '', index: '' }],//测量信息
    other_cooker_num: '',//其他炉具数量
    chooseType: 1,//上传类型，1图片，2视频
    videoUrl: '',//显示用的
    video_url: '',//传给服务器用的
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var that = this;
    that.headid = this.selectComponent("#addressid"); //引入地址
    that.getSearchConfig();//灶眼
    that.getStoveConfig();//炉具类型
    that.getRangeTime(options.id);//上门日期限制
    that.setData({
      work_order_id: options.id ? options.id : ''
    })

  },
  /*** 生命周期函数--监听页面显示*/
  onShow: function () {
    canDo = true;
  },
  // 订单详情
  getOrderDetail: function (id, time_list, configData) {
    var that = this;
    app.ajax({
      url: 'Engineer/Workorder/workOrderDetail',
      data: { work_order_id: id },
      success: function (res) {
        if (res.data.code == 1000) {
          var getData = res.data.data;
          var checkTimeId = getData.appointment_time_id;
          var cooker_chose = getData.cooker_type;//炉具类型
          var scene_chose = getData.scene_type;//场景
          //上门时间回显
          time_list.forEach((item, index) => {
            if (checkTimeId == item.time_id) {
              that.setData({ time_index: index })
              appointment_time_id = item.time_id
            }
          })

          //服务场景回显
          configData.scene_type.forEach((item, index) => {
            if (scene_chose == item.id) {
              that.setData({ server_index: index })
              scene_id = item.id
            }
          })


          //地址信息回显.
          var getAreaMsg = {
            areaId: [getData.province_code, getData.city_code, getData.area_code],
            areaName: [getData.province, getData.city, getData.area]
          };

          that.setData({
            valueName: getAreaMsg.areaName,
            orderDetail: getData,
            to_door: getData.appointment_time,
            buy_date: getData.cooker_purchase_time,
            imgUrl: getData.whole_url_img,
            img_url: getData.img,//上传后台
            videoUrl: getData.video_url,
            video_url: getData.video,//上传后台
            add_ress: getData.service_address,
            fanArr: getData.draught_fan.length > 0 ? getData.draught_fan : [{ power: '', focal_eye: '', focal_eye_name: '', index: '' }],
            cookerArr: getData.cooker_type.length > 0 ? getData.cooker_type : [{ cooker_type: '', cooker_type_name: '', num: 1, water_quantity: '', gas_consumption: '', second: '', index: '' }],
            other_cooker_num: getData.other_cooker_num,
            getAreaMsg
          });
          ch_latitude = getData.lat;
          ch_longitude = getData.lng;
        }
      }
    })

  },
  /*** 生命周期函数--监听页面卸载 重置全局变量我也不知道为什么要用全局变量*/
  onUnload: function () {
    appointment_time_id = '';
    scene_id = '';
    cooker_id = "";
    ch_latitude = "";
    ch_longitude = "";
  },
  //获取时间段以及限制
  getRangeTime(id) {
    var that = this;
    app.ajax({
      url: 'Common/Common/getRangeTime',
      method: "POST",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            time_list: res.data.data.time,
            start_time: res.data.data.date.start,
            end_time: res.data.data.date.end,
          })
        } else {
          app.showToast(res.data.message);
        }
        that.appointmentConfiguration(id, that.data.time_list);//服务场景

      }
    })
  },
  //获取炉具类型下拉选项
  getStoveConfig() {
    var that = this;
    app.ajax({
      url: 'Common/Common/getStoveConfig',
      method: "POST",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            cooker_list: res.data.data
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //系统配置下拉选项
  appointmentConfiguration(id, time_list) {
    var that = this;
    app.ajax({
      url: 'Common/Common/appointmentConfiguration',
      method: "POST",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            server_list: res.data.data.scene_type,
          })
        } else {
          app.showToast(res.data.message);
        }
        that.getOrderDetail(id, time_list, res.data.data);
      }
    })
  },
  //灶眼配置下拉选项
  getSearchConfig() {
    var that = this;
    app.ajax({
      url: 'Common/Common/getSearchConfig',
      method: "POST",
      data: { config_name: "a_few_eyes" },
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            focal_eye_list: res.data.data,
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //服务场景
  bindServerPicker(e) {
    var that = this;
    this.setData({
      server_index: e.detail.value
    })
    scene_id = that.data.server_list[e.detail.value].id
  },
  //炉具类型
  bindCookerPicker(e) {
    let { index } = e.currentTarget.dataset;
    let cookerArr = this.data.cookerArr;
    cookerArr[index].index = e.detail.value;
    cookerArr[index].cooker_type = this.data.cooker_list[index].id;
    cookerArr[index].cooker_type_name = this.data.cooker_list[index].name;
    cookerArr[index].water_quantity = this.data.cooker_list[index].water_quantity;
    this.setData({ cookerArr });
  },
  //灶眼选择
  bindFocalEyePicker(e) {
    let { index } = e.currentTarget.dataset;
    let fanArr = this.data.fanArr;
    fanArr[index].index = e.detail.value;
    fanArr[index].focal_eye = this.data.focal_eye_list[index].id;
    fanArr[index].focal_eye_name = this.data.focal_eye_list[index].name;
    this.setData({ fanArr });
  },

  //上门日期
  startDateChange: function (e) {
    this.setData({
      to_door: e.detail.value
    })
  },
  //选择时间段
  bindPickerChange: function (e) {
    let that = this;
    let time_index = e.detail.value;
    var time_list = that.data.time_list;
    var t_id = time_list[time_index].time_id;
    that.setData({
      time_index: time_index
    })
    appointment_time_id = t_id;
  },
  //购买时间
  buyDateChange: function (e) {
    this.setData({
      buy_date: e.detail.value
    })
  },
  //选择地址
  openAeraFun() {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        console.info(res);
        that.setData({
          add_ress: res.name
        })
        ch_latitude = res.latitude;
        ch_longitude = res.longitude;
      },
    })
  },
  //打开地图选择
  openAddress() {
    var that = this;
    this.headid.startAddressAnimation(true);
  },
  //确定接受
  getSure(data) {
    var that = this;
    let [province_code, city_code, area_code] = data.detail.areaId;
    let [province, city, area] = data.detail.areaName;
    that.setData({
      getAreaMsg: data.detail
    })
  },

  //添加风机功率
  addFanBtn() {
    var fanArr = this.data.fanArr;
    if (fanArr.length > 99) {
      return false;
    }
    var obj = { power: '', focal_eye: '', focal_eye_name: '', index: '' };
    fanArr.push(obj);
    this.setData({ fanArr })
  },
  //删除风机功率
  cutFanBtn(e) {
    let { index } = e.currentTarget.dataset;
    let fanArr = this.data.fanArr;
    fanArr.splice(index, 1);
    this.setData({ fanArr })
  },
  //添加炉具
  addCookerBtn() {
    var cookerArr = this.data.cookerArr;
    if (cookerArr.length > 99) {
      return false;
    }
    var obj = { cooker_type: '', cooker_type_name: '', num: 1, water_quantity: '', gas_consumption: '', second: '', index: '' };
    cookerArr.push(obj);
    this.setData({ cookerArr })
  },
  //删除炉具
  cutCookerBtn(e) {
    let { index } = e.currentTarget.dataset;
    let cookerArr = this.data.cookerArr;
    cookerArr.splice(index, 1);
    this.setData({ cookerArr })
  },
  //监听输入
  inputFan(e) {
    let { index } = e.currentTarget.dataset;
    let fanArr = this.data.fanArr;
    fanArr[index].power = e.detail.value;
    this.setData({ fanArr })
  },
  //监听炉具水量输入
  inputCooker1(e) {
    let { index } = e.currentTarget.dataset;
    let cookerArr = this.data.cookerArr;
    cookerArr[index].water_quantity = e.detail.value;
    this.setData({ cookerArr })
  },
  //监听炉具燃气输入
  inputCooker2(e) {
    let { index } = e.currentTarget.dataset;
    let cookerArr = this.data.cookerArr;
    cookerArr[index].gas_consumption = e.detail.value;
    this.setData({ cookerArr })
  },
  //监听炉具时间输入
  inputCooker3(e) {
    let { index } = e.currentTarget.dataset;
    let cookerArr = this.data.cookerArr;
    cookerArr[index].second = e.detail.value;
    this.setData({ cookerArr })
  },
  //监听炉具数量输入
  inputCooker4(e) {
    let { index } = e.currentTarget.dataset;
    let cookerArr = this.data.cookerArr;
    cookerArr[index].num = e.detail.value;
    this.setData({ cookerArr })
  },

  // 添加图片 打开中间页
  openChoose(e) {
    var that = this;
    that.setData({
      isShow: true,
      chooseType: e.currentTarget.dataset.choose
    })
  },
  //关闭中间页(关闭)
  closeShoot() {
    var that = this;
    that.setData({
      isShow: false,
    })
  },
  //打开相机
  openAbout(e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    //关闭中间页面 打开自定义照相机
    that.setData({
      isShow: false,
    })
    var length = that.data.imgUrl.length || 0;
    var count = 9 - length;
    var sourceType = '';
    if (type == 1) {
      sourceType = 'album';
    } else if (type == 2) {
      sourceType = 'camera';
    }
    if (that.data.chooseType == 1) {//图片
      wx.chooseImage({
        count: count,
        sizeType: ['compressed'],
        sourceType: [sourceType],
        success: function (res) {
          const tempFilePaths = res.tempFilePaths;
          wx.showLoading({
            mask: true,
            title: '上传中',
          })
          that.uploadImageArr(tempFilePaths);
        },
      })
    } else {//视频
      wx.chooseVideo({
        sourceType: [sourceType],
        compressed: true,
        maxDuration: 60,
        camera: 'back',
        success: function (res) {
          if (res.duration > 60) {
            app.showToast('视频时长必须小于60秒');
            return
          }
          const tempFilePath = res.tempFilePath;
          wx.showLoading({
            mask: true,
            title: '上传中',
          })
          that.uploadImageArr([tempFilePath]);
        },
      })
    }
  },
  // 上传头图
  uploadImageArr(tempFilePaths) {
    var that = this;
    for (var i in tempFilePaths) {
      wx.uploadFile({
        url: app.globalData._url + 'Common/Common/upload',
        filePath: tempFilePaths[i],
        header: {
          'appid': app.globalData.appid
        },
        name: 'file',
        success: function (result) {
          if (result.statusCode !== 200) {
            wx.hideLoading();
            app.showToast('上传失败,请重新上传');
            return
          }
          var data = JSON.parse(result.data);
          if (data.code == 1000) {
            if (that.data.chooseType == 1) {//图片
              var imgUrl = that.data.imgUrl;
              var img_url = that.data.img_url;
              imgUrl.push(data.data.all_url);
              img_url.push(data.data.url);
              that.setData({
                imgUrl,
                img_url
              })
              wx.hideLoading();
            } else {//视频
              var videoUrl = data.data.all_url;
              var video_url = data.data.url;
              that.setData({
                videoUrl,
                video_url
              })
              wx.hideLoading();
            }
          } else {
            wx.hideLoading();
            app.showToast('上传失败,请重新上传');
          }
        },
        fail: function (fail) {
          wx.hideLoading();
          app.showToast('上传失败,请重新上传');
        }
      })
    }
  },
  // 图片放大预览
  previewImage(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.url,
      urls: this.data.imgUrl // 需要预览的图片http链接列表
    })
  },
  // 删除图片
  reduceImg(e) {
    var imgUrl = this.data.imgUrl;
    var img_url = this.data.img_url;
    var index = e.currentTarget.dataset.index;
    imgUrl.splice(index, 1);
    img_url.splice(index, 1);
    this.setData({
      imgUrl,
      img_url
    })
    // this.changeSubmit();
  },
  //删除视频
  reduceVideo() {
    this.setData({
      videoUrl: '',
      video_url: '',
    })
  },

  //提交表单
  formSubmit(e) {
    let that = this;
    let type = e.detail.target.dataset.type;
    //这是关闭该订单
    if (type == 0) {
      wx.navigateBack({
        delta: 1
      })
      // wx.showModal({
      //   title: '是否取消确认工单?',
      //   content: '',
      //   confirmColor: '#DF0101',
      //   success(res) {
      //     if (res.confirm) {
      //       wx.navigateBack({
      //         delta: 1
      //       })
      //       // that.closeSurveyWork(e);//调用关闭工单接口
      //     } else if (res.cancel) {

      //     }

      //   }
      // })
    } else {
      wx.showModal({
        title: '是否确认炉具信息完毕?',
        content: '',
        confirmColor: '#DF0101',
        success(res) {
          if (res.confirm) {
            that.newClothesWrok(e);//正常转成新装工单
          } else if (res.cancel) {

          }

        }
      })
    }

  },
  //转换成功
  newClothesWrok(e) {
    var that = this;
    let formVal = e.detail.value;
    let fanArr = that.data.fanArr;
    let [province_code, city_code, area_code] = that.data.getAreaMsg.areaId ? that.data.getAreaMsg.areaId : '';
    let [province, city, area] = that.data.getAreaMsg.areaName ? that.data.getAreaMsg.areaName : '';
    let numreg = /^[1][3-9][\d]{9}$/; //手机号码正则
    if (formVal.contacts == '') {
      app.showToast('姓名不能为空', "none", 2000, function () { });
      return false;
    }
    if (formVal.contacts == '') {
      app.showToast('手机号码不能为空', "none", 2000, function () { });
      return false;
    }
    if (numreg.test(formVal.contact_number) == false || formVal.contact_number.length < 11) {
      app.showToast('请输入正确的手机号码', "none", 2000, function () { });
      return false;
    }
    // if (formVal.appointment_date == '') {
    //   app.showToast('请选择上门日期', "none", 2000, function () { });
    //   return false;
    // }
    // if (formVal.appointment_date == '') {
    //   app.showToast('请选择上门日期', "none", 2000, function () { });
    //   return false;
    // }
    // if (appointment_time_id == '') {
    //   app.showToast('请选择上门时间', "none", 2000, function () { });
    //   return false;
    // }
    if (scene_id == '') {
      app.showToast('请选择服务场景', "none", 2000, function () { });
      return false;
    }

    if (that.data.getAreaMsg == '') {
      app.showToast('请选择省市区', "none", 2000, function () { });
      return false;
    }
    if (ch_latitude == '' || ch_longitude == '') {
      app.showToast('请选择安装位置信息', "none", 2000, function () { });
      return false;
    }


    let updata = {
      work_order_id:that.data.work_order_id,
      contacts: formVal.contacts,
      contact_number: formVal.contact_number,
      appointment_date: formVal.appointment_date,
      appointment_time_id: appointment_time_id,
      scene_type: scene_id,
      cooker_type: that.data.cookerArr,
      other_cooker_num: formVal.other_cooker_num,
      cooker_brand: formVal.cooker_brand,
      cooker_model_number: formVal.cooker_model_number,
      cooker_num: formVal.cooker_num,
      expected_renovation_num: formVal.expected_renovation_num,
      cooker_purchase_time: formVal.cooker_purchase_time,
      gas_fee: formVal.gas_fee,
      province,
      province_code,
      city,
      city_code,
      area,
      area_code,
      address: formVal.address,
      lat: ch_latitude,
      lng: ch_longitude,
      img: that.data.img_url,
      video: that.data.video_url,
      draught_fan: fanArr,
      user_remarks: formVal.user_remarks,
      repair_remarks: formVal.repair_remarks,
    }
    if (!canDo) {
      return false
    }
    canDo = false;
    app.ajax({
      url: 'Engineer/Workorder/confirmCookerInformation',
      data: updata,
      success: function (res) {
        if (res.data.code == 1000) {
          app.showToast('确认炉具信息成功!');
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            })
          }, 1000)
        } else {
          app.showToast(res.data.message, "none", 2000, function () { });
        }
        setTimeout(() => {
          canDo = true;
        }, 1000)
      }
    })
  },

  //关闭勘察工单
  closeSurveyWork(e) {
    var that = this;
    let formVal = e.detail.value;
    let fanArr = that.data.fanArr;
    let [province_code, city_code, area_code] = that.data.getAreaMsg.areaId ? that.data.getAreaMsg.areaId : '';
    let [province, city, area] = that.data.getAreaMsg.areaName ? that.data.getAreaMsg.areaName : '';

    let updata = {
      work_order_id: that.data.work_order_id,
      contacts: formVal.contacts,
      contact_number: formVal.contact_number,
      appointment_date: formVal.appointment_date,
      appointment_time_id: appointment_time_id,
      scene_type: scene_id,
      cooker_type: that.data.cookerArr,
      other_cooker_num: formVal.other_cooker_num,
      cooker_brand: formVal.cooker_brand,
      cooker_model_number: formVal.cooker_model_number,
      cooker_num: formVal.cooker_num,
      expected_renovation_num: formVal.expected_renovation_num,
      cooker_purchase_time: formVal.cooker_purchase_time,
      gas_fee: formVal.gas_fee,
      province,
      province_code,
      city,
      city_code,
      area,
      area_code,
      address: formVal.address,
      lat: ch_latitude,
      lng: ch_longitude,
      img: that.data.img_url,
      video: that.data.video_url,
      draught_fan: fanArr,
      user_remarks: formVal.user_remarks,
      repair_remarks: formVal.repair_remarks,
    }
    if (!can_Do2) {
      return false
    }
    can_Do2 = false;
    app.ajax({
      url: 'Engineer/Workorder/closeOrder',
      method: "POST",
      data: updata,
      success: function (res) {
        //console.log(res)
        if (res.data.code == 1000) {
          app.showToast('订单关闭成功!');
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            })
          }, 1000)

        } else {
          app.showToast(res.data.message);
        }
        setTimeout(() => {
          can_Do2 = true;
        }, 1000)
      }
    })

  },


})
